package com.dkd.service.impl;
import cn.elegent.token.context.ElegentTokenContext;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.dkd.config.constant.TaskStatus;
import com.dkd.config.constant.TaskType;
import com.dkd.config.constant.VmStatus;
import com.dkd.contract.SupplyContract;
import com.dkd.dao.TaskDao;
import com.dkd.entity.TaskDetailsEntity;
import com.dkd.entity.TaskEntity;
import com.dkd.entity.TaskStatusTypeEntity;
import com.dkd.exception.LogicException;
import com.dkd.feign.UserService;
import com.dkd.feign.VMService;
import com.dkd.http.vo.*;
import com.dkd.service.TaskDetailsService;
import com.dkd.service.TaskService;
import com.dkd.service.TaskStatusTypeService;
import com.dkd.vo.Pager;
import com.dkd.vo.UserVO;
import com.dkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao,TaskEntity> implements TaskService{

    @Autowired
    private TaskStatusTypeService statusTypeService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private VMService vmService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskDetailsService taskDetailsService;


    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex,pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if(!Strings.isNullOrEmpty(innerCode)){
            qw.eq(TaskEntity::getInnerCode,innerCode);
        }
        if(userId != null && userId > 0){
            qw.eq(TaskEntity::getUserId,userId);
        }
        if(!Strings.isNullOrEmpty(taskCode)){
            qw.like(TaskEntity::getTaskCode,taskCode);
        }
        if(status != null && status > 0){
            qw.eq(TaskEntity::getTaskStatus,status);
        }
        if(isRepair != null){
            if(isRepair){
                qw.ne(TaskEntity::getProductTypeId, TaskType.TASK_TYPE_SUPPLY);
            }else {
                qw.eq(TaskEntity::getProductTypeId,TaskType.TASK_TYPE_SUPPLY);
            }
        }
        if(!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)){
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime,LocalDate.parse(end,DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page,qw));
    }



    @Override
    public List<TaskStatusTypeEntity> getAllStatus() {
        QueryWrapper<TaskStatusTypeEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .ge(TaskStatusTypeEntity::getStatusId, TaskStatus.TASK_STATUS_CREATE);

        return statusTypeService.list(qw);
    }


    @Transactional
    @Override
    public boolean createTask(TaskViewModel taskViewModel) throws LogicException {
        Integer userId =  Integer.parseInt(ElegentTokenContext.getUserId());  //获取用户id

        taskViewModel.setAssignorId( userId);//设置当前登录用户id为指派人id
        if(hasTask(taskViewModel.getInnerCode(),taskViewModel.getProductType())) {
            throw new LogicException("该机器有未完成的同类型工单");
        }
        //跨服务查询售货机微服务，得到售货机的地址和区域id
        VmVO vm = vmService.getVMInfo(taskViewModel.getInnerCode());
        if(vm==null){
            throw new LogicException("该机器不存在");
        }
        checkCreateTask(vm.getVmStatus(),taskViewModel.getProductType());//验证售货机状态
        //跨服务查询用户微服务，得到用户名
        UserVO user = userService.getUser(taskViewModel.getUserId());
        if(user==null){
            throw new LogicException("该用户不存在");
        }

        //新增工单表记录
        TaskEntity taskEntity = new TaskEntity();
        taskEntity.setTaskCode(generateTaskCode());//工单编号
        BeanUtils.copyProperties(taskViewModel,taskEntity);//复制属性
        taskEntity.setTaskStatus(TaskStatus.TASK_STATUS_CREATE);//工单状态
        taskEntity.setProductTypeId(taskViewModel.getProductType());//工单类型

        taskEntity.setAddr(vm.getNodeAddr());//地址
        taskEntity.setRegionId(  vm.getRegionId() );//区域
        taskEntity.setUserName(user.getUserName());//用户名
        this.save(taskEntity);
        //如果是补货工单，向 工单明细表插入记录
        if(taskEntity.getProductTypeId() == TaskType.TASK_TYPE_SUPPLY){
            taskViewModel.getDetails().forEach(d->{
                TaskDetailsEntity detailsEntity = new TaskDetailsEntity();
                BeanUtils.copyProperties( d,detailsEntity );
                detailsEntity.setTaskId(taskEntity.getTaskId());
                taskDetailsService.save(detailsEntity);
            });
        }
        return true;
    }

    @Override
    public TaskViewModel buildTaskViewModel(int userId ,SupplyContract supplyContract) {
        //创建补货工单
        var taskViewModel = new TaskViewModel();
        taskViewModel.setUserId(userId);
        taskViewModel.setCreateType(0);//创建类型
        taskViewModel.setProductType(TaskType.TASK_TYPE_SUPPLY);
        taskViewModel.setInnerCode(supplyContract.getInnerCode());
        taskViewModel.setAssignorId(0);//创建人
        taskViewModel.setDesc("自动补货工单");
        taskViewModel.setDetails(supplyContract.getSupplyData().stream().map(c -> {
            var taskDetailsViewModel = new TaskDetailsViewModel();
            taskDetailsViewModel.setChannelCode(c.getChannelId());
            taskDetailsViewModel.setExpectCapacity(c.getCapacity());
            taskDetailsViewModel.setSkuId(c.getSkuId());
            taskDetailsViewModel.setSkuName(c.getSkuName());
            taskDetailsViewModel.setSkuImage(c.getSkuImage());
            return taskDetailsViewModel;
        }).collect(Collectors.toList()));  //补货详情
        return taskViewModel;
    }


    /**
     * 生成工单编号
     * @return
     */
    private String generateTaskCode(){
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));  //日期字符串
        String key= "dkd.task.code."+date; //redis key
        Object obj = redisTemplate.opsForValue().get(key);
        if(obj==null){
            redisTemplate.opsForValue().set(key,1L, Duration.ofDays(1) );
            return date+"0001";
        }
        return date+  Strings.padStart( redisTemplate.opsForValue().increment(key,1).toString(),4,'0');
    }


    @Override
    public boolean accept(Long id) {
        TaskEntity task = this.getById(id);  //查询工单
        Integer userId =  Integer.parseInt(ElegentTokenContext.getUserId());  //获取用户id
        //判断工单执行人是否为当前登录用户
        if(task.getUserId().intValue()!=userId){
            throw new LogicException("操作非法");
        }
        if(task.getTaskStatus()!= TaskStatus.TASK_STATUS_CREATE ){
            throw new LogicException("工单状态不是待处理");
        }
        task.setTaskStatus( TaskStatus.TASK_STATUS_PROGRESS );//修改工单状态为进行
        return this.updateById(task);
    }

    @Override
    public boolean cancelTask(Long id, CancelTaskViewModel cancelVM) {
        TaskEntity task = this.getById(id);  //查询工单
        Integer userId =  Integer.parseInt(ElegentTokenContext.getUserId());  //获取用户id
        //判断工单执行人是否为当前登录用户 判断工单指派人是否未当前登录用户
        if(!(task.getUserId().intValue()==userId.intValue() || task.getAssignorId().intValue()==userId.intValue() )  )  {
            throw new LogicException("操作非法");
        }
        if(task.getTaskStatus()== TaskStatus.TASK_STATUS_FINISH  || task.getTaskStatus()== TaskStatus.TASK_STATUS_CANCEL ){
            throw new LogicException("工单已经结束");
        }
        task.setTaskStatus( TaskStatus.TASK_STATUS_CANCEL  );
        task.setDesc(cancelVM.getDesc());
        return this.updateById(task);
    }

    @Override
    public boolean completeTask(long id) {
        TaskEntity taskEntity = this.getById(id);
        Integer userId =  Integer.parseInt(ElegentTokenContext.getUserId());  //获取用户id
        //判断工单执行人是否为当前登录用户
        if(taskEntity.getUserId().intValue()!=userId.intValue() ){
            throw new LogicException("操作非法");
        }
        //判断工单状态
        if(taskEntity.getTaskStatus()== TaskStatus.TASK_STATUS_FINISH  || taskEntity.getTaskStatus()== TaskStatus.TASK_STATUS_CANCEL ){
            throw new LogicException("工单已经结束");
        }
        taskEntity.setTaskStatus(TaskStatus.TASK_STATUS_FINISH);//修改工单状态
        this.updateById(taskEntity);
        return true;
    }

    /**
     * 统计工单数量
     * @param start
     * @param end
     * @param repair 是否是运维工单
     * @param taskStatus
     * @return
     */
    private int taskCount(LocalDateTime start, LocalDateTime end , Boolean repair , Integer taskStatus ){
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        qw.ge(TaskEntity::getUpdateTime,start)
                .le(TaskEntity::getUpdateTime,end);
        //按工单状态查询
        if(taskStatus!=null){
            qw.eq(TaskEntity::getTaskStatus,taskStatus);
        }
        if(repair){//如果是运维工单
            qw.ne(TaskEntity::getProductTypeId,TaskType.TASK_TYPE_SUPPLY);
        }else{
            qw.eq(TaskEntity::getProductTypeId,TaskType.TASK_TYPE_SUPPLY);
        }
        return this.count(qw);
    }


    @Override
    public List<TaskReportInfoVO> getTaskReportInfo(LocalDateTime start, LocalDateTime end) {

        //运营工单总数total
        var supplyTotal = this.taskCount( start,end,false, null );
        //运维工单总数
        var repairTotal = this.taskCount( start,end,true, null );
        //完成的运营工单总数
        var completedSupply = this.taskCount( start,end,false, TaskStatus.TASK_STATUS_FINISH );
        //完成的运维工单总数
        var completedRepair = this.taskCount( start,end,true, TaskStatus.TASK_STATUS_FINISH );
        //拒绝掉的运营工单总数
        var cancelSupply = this.taskCount( start,end,false, TaskStatus.TASK_STATUS_CANCEL );
        //拒绝掉的运维工单总数
        var cancelRepair = this.taskCount( start,end,true, TaskStatus.TASK_STATUS_CANCEL );
        // 获取运营人员数量
        var operatorCount = userService.getOperatorCount();
        //获取运维人员总数
        var repairerCount = userService.getRepairerCount();

        List<TaskReportInfoVO> result = Lists.newArrayList();

        //运营人员
        var supplyTaskInfo = new TaskReportInfoVO();
        supplyTaskInfo.setTotal(supplyTotal);
        supplyTaskInfo.setCancelTotal(cancelSupply);
        supplyTaskInfo.setCompletedTotal(completedSupply);
        supplyTaskInfo.setRepair(false);
        supplyTaskInfo.setWorkerCount(operatorCount);
        result.add(supplyTaskInfo);

        //运维人员
        var repairTaskInfo = new TaskReportInfoVO();
        repairTaskInfo.setTotal(repairTotal);
        repairTaskInfo.setCancelTotal(cancelRepair);
        repairTaskInfo.setCompletedTotal(completedRepair);
        repairTaskInfo.setRepair(true);
        repairTaskInfo.setWorkerCount(repairerCount);
        result.add(repairTaskInfo);
        return result;
    }

    /**
     * 按时间和状态进行统计
     * @param start
     * @param taskStatus
     * @return
     */
    private int count(LocalDate start ,Integer taskStatus){
        var qw = new LambdaQueryWrapper<TaskEntity>();
        qw
                .ge(TaskEntity::getUpdateTime,start)
                .lt(TaskEntity::getUpdateTime,start.plusDays(1))
                .eq(TaskEntity::getTaskStatus, taskStatus);
        return this.count(qw);
    }


    /**
     * 创建工单校验
     * @param vmStatus
     * @param productType
     * @throws LogicException
     */
    private void checkCreateTask(Integer vmStatus,int productType) throws LogicException {
        //如果是投放工单，状态为运营
        if(productType == TaskType.TASK_TYPE_DEPLOY  && vmStatus == VmStatus.VM_STATUS_RUNNING){
            throw new LogicException("该设备已在运营");
        }

        //如果是补货工单，状态不是运营状态
        if(productType == TaskType.TASK_TYPE_SUPPLY  && vmStatus != VmStatus.VM_STATUS_RUNNING){
            throw new LogicException("该设备不在运营状态");
        }

        //如果是撤机工单，状态不是运营状态
        if(productType == TaskType.TASK_TYPE_REVOKE  && vmStatus != VmStatus.VM_STATUS_RUNNING){
            throw new LogicException("该设备不在运营状态");
        }
    }


    /**
     * 同一台设备下是否存在未完成的工单
     * @param innerCode
     * @param productionType
     * @return
     */
    @Override
    public boolean hasTask(String innerCode,int productionType){
        QueryWrapper<TaskEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .select(TaskEntity::getTaskId)
                .eq(TaskEntity::getInnerCode,innerCode)
                .eq(TaskEntity::getProductTypeId,productionType)
                .le(TaskEntity::getTaskStatus,TaskStatus.TASK_STATUS_PROGRESS);
        return this.count(qw) > 0;
    }





    @Override
    public int getLeastUser(Long regionId, Boolean isRepair) {
        QueryWrapper<TaskEntity> qw = new QueryWrapper<>();
        qw.select("user_id","IFNULL(count(user_id),0) as task_id" )
            .lambda()
            .eq(TaskEntity::getRegionId,regionId)  //区域id
            .ne(TaskEntity::getTaskStatus,TaskStatus.TASK_STATUS_CANCEL)//取消的不算
            .ge(TaskEntity::getCreateTime,LocalDate.now())
            .groupBy( TaskEntity::getUserId  )//根据员工id分组
            .orderByAsc(TaskEntity::getTaskId); //这里的taskid指的是统计的工单数
        if(isRepair){
            qw.lambda().ne(TaskEntity::getProductTypeId,TaskType.TASK_TYPE_SUPPLY);
        }else {
            qw.lambda().eq(TaskEntity::getProductTypeId,TaskType.TASK_TYPE_SUPPLY);
        }
        List<TaskEntity> taskList = this.list(qw);  //获取该区域的当日员工工单数列表
        List<UserVO> userList;
        if(isRepair) {
            userList = userService.getRepairers(regionId); //运维
        }else{
            userList = userService.getOperators(regionId);//运营
        }
        //用户列表
        List<Integer> userIdList = taskList.stream().map(taskEntity -> taskEntity.getUserId()).collect(Collectors.toList());
        //找出userList存在，但是taskList不存在的，也就是没有工单的id
        List<UserVO> noWorkUserList = userList.stream().filter(userVO -> !userIdList.contains(userVO.getUserId()) ).collect(Collectors.toList());
        if(noWorkUserList.size()>0){  //如果存在没有工单的用户
            return noWorkUserList.get(0).getUserId();
        }else{  //如果大家都有工单
            return taskList.get(0).getUserId();  //返回最少工单的用户
        }
    }

    /**
     * 修改工单的状态为进行中
     * @param taskEntity
     */
    @Override
    public void rollbackTaskState(TaskEntity taskEntity) {
        LambdaUpdateWrapper<TaskEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(TaskEntity::getTaskId,taskEntity.getTaskId());
        updateWrapper.set(TaskEntity::getTaskStatus,TaskStatus.TASK_STATUS_CANCEL);
        this.update(updateWrapper);
    }
}
